package com.cn.mmd.controller;

import com.cn.mmd.model.Student;
import com.cn.mmd.model.StudentApp;
import com.cn.mmd.model.StudentIntegral;
import com.cn.mmd.service.StudentAppService;

import com.cn.mmd.service.StudentIntegralService;
import com.cn.mmd.service.StudentService;
import com.cn.mmd.tools.AliyunOssUtil;
import com.sun.tools.internal.ws.processor.model.Model;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2016/7/21 0021.
 */

@Controller
@RequestMapping(value = "page/studentApp")
public class StudentAppController {

    @Autowired
    private StudentAppService studentAppService;

    @Autowired
    private TokenController tokenController;

    @Autowired
    private StudentService studentService;

    @Autowired
    private StudentIntegralService studentIntegralService;

    /**
     * 修改密码
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/updPassword")
    @ResponseBody
    public synchronized Object updPassWord(HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        String studentId = request.getParameter("studentId");
        String password = request.getParameter("password");
        String password1 = request.getParameter("password1");
        String password2 = request.getParameter("password2");
        String token = request.getParameter("token");
        StudentApp studentApp;
        studentApp = (StudentApp) tokenController.token1(studentId, token);
        if (studentApp != null) {
            if (DigestUtils.md5Hex(password).equals(studentApp.getStudentpassword())) {
                if (password1.equals(password2)) {
                    studentApp = new StudentApp();
                    studentApp.setStudentid(studentId);
                    studentApp.setStudentpassword(DigestUtils.md5Hex(password1));
                    if (studentAppService.updateByPrimaryKeySelective(studentApp) > 0) {
                        objectMap.put("code", 200);
                        objectMap.put("message", "修改成功");
                    } else {
                        objectMap.put("code", 201);
                        objectMap.put("message", "修改失败请核对信息是否正确");
                    }
                } else {
                    objectMap.put("code", 202);
                    objectMap.put("message", "2次密码不一致");
                }
            } else {
                objectMap.put("code", 203);
                objectMap.put("message", "密码不正确");
            }
        }else {
            objectMap.put("code", 204);
            objectMap.put("message", "此用户没有权限做此操作");
        }
        return objectMap;
    }

    @RequestMapping(value = "/selectMe")
    @ResponseBody
    public synchronized Object selectMe(HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        String studentId = request.getParameter("studentId");
        String token = request.getParameter("token");
        StudentApp studentApp;
        studentApp = (StudentApp) tokenController.token1(studentId, token);
        Student student = studentService.selectByPrimaryKey(studentId);
        if (studentApp != null && student != null) {
            map.put("myNickName", studentApp.getMynickname());
            map.put("viewedNum", studentApp.getViewednum());
            map.put("downloadNum", studentApp.getDownloadnum());
            map.put("commentNum", studentApp.getCommentnum());
            map.put("myBirthd", studentApp.getMybirthd());
            map.put("personalizedSignature", studentApp.getPersonalizedsignature());
            map.put("studentHeadPortrait", studentApp.getStudentheadportrait());
            map.put("studentPhoneNumber", studentApp.getStudentphonenumber());
            map.put("studentSex", studentApp.getStudentsex());
            map.put("studentPassword", studentApp.getStudentpassword());
            map.put("studentName", studentApp.getStudentname());
            map.put("studentClass", student.getStudentcollege() + student.getStudentmajor() + "专业" + student.getStudentclasss() + student.getStudentclass());
            StudentIntegral studentIntegral = studentIntegralService.selectByPrimaryKey(studentId);
            if (studentIntegral!=null) {
                map.put("studentExperience",studentIntegral.getScore());
                map.put("studentExperienceMax",studentIntegral.getUpgrade());
                map.put("studentIntegralGrade",studentIntegral.getGrade());
                map.put("studentLotteryNumber",studentIntegral.getLotterynumber());
            }else {
                map.put("studentExperience",0);
                map.put("studentExperienceMax",0);
                map.put("studentIntegralGrade",0);
                map.put("studentLotteryNumber",0);
            }
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                String studentAge;
                if (studentApp.getMybirthd() != null&&!studentApp.getMybirthd().equals("")) {
                    studentAge = ((date.getTime() - sdf.parse(studentApp.getMybirthd()).getTime()) / (1000 * 60 * 60 * 24) / 365) + "";
                    map.put("studentAge", studentAge + "");
                } else {
                    map.put("studentAge", "");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            objectMap.put("data", map);
            objectMap.put("code", 200);
            objectMap.put("message", "成功");
        } else {
            objectMap.put("code", 201);
            objectMap.put("message", "不存在此学生");
        }
        return objectMap;
    }


    @RequestMapping(value = "/updMe")
    @ResponseBody
    public synchronized Object updMe(HttpServletRequest request,
                        @RequestParam(value = "studentHeadPortrait", required = false) MultipartFile file) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        String studentId = request.getParameter("studentId");
        String personalizedSignature = request.getParameter("personalizedSignature");
        String studentPhoneNumber = request.getParameter("studentPhoneNumber");
        String studentSex = request.getParameter("studentSex");
        String myBirthd = request.getParameter("myBirthd");
        String myNickName = request.getParameter("myNickName");
        String token = request.getParameter("token");
        StudentApp studentApp;
        studentApp = (StudentApp) tokenController.token1(studentId, token);
        if (studentApp != null) {
            String path = request.getSession().getServletContext().getRealPath("/") + "upload";
            File targetFile;
            String studentHeadPortraitUrl = studentApp.getStudentheadportrait();
            System.out.println(file+"-----");
            if (file != null&&!file.getOriginalFilename().equals("")) {
                String key = studentId + "-HeadPortrait-" + file.getOriginalFilename();
                targetFile = new File(path, key);
                if (!targetFile.exists()) {
                    try {
                        file.transferTo(targetFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    targetFile.delete();
                    try {
                        file.transferTo(targetFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                studentHeadPortraitUrl = AliyunOssUtil.save(key, targetFile.getPath());
                targetFile.delete();
            }
            studentApp = new StudentApp();
            studentApp.setStudentid(studentId);
            studentApp.setStudentphonenumber(studentPhoneNumber);
            studentApp.setStudentsex(studentSex);
            studentApp.setMynickname(myNickName);
            studentApp.setMybirthd(myBirthd);
            studentApp.setPersonalizedsignature(personalizedSignature);
            studentApp.setStudentheadportrait(studentHeadPortraitUrl);
            if (studentAppService.updateByPrimaryKeySelective(studentApp) > 0) {
                objectMap.put("code", 200);
                objectMap.put("message", "成功");
            } else {
                objectMap.put("code", 201);
                objectMap.put("message", "修改失败");
            }
        }else {
            objectMap.put("code", 202);
            objectMap.put("message", "此用户没有权限做此操作");
        }
        return objectMap;
    }
}
